# TODO: Add comment
# 
# Author: guochun
###############################################################################


plotdim=c(600,500)
#定义基本取样网格大小，现在是20×20m，图中用黑色点表示
x=seq(0,600,20)
y=seq(0,500,20)
#定义每个基本取样点延伸出去的点的距离，现在设置是离基准点1、5、12米，图中分别用绿、红和蓝点表示
d=c(1,5,12)

grid=expand.grid(x=x,y=y)
angles=rep(pi/4,8)*c(1:8)


samples=matrix(nrow=0,ncol=2)
fromto=matrix(nrow=0,ncol=4)
changex=c(1,0,-1,-1,-1,0,1,1)
changey=c(1,1,1,0,-1,-1,-1,0)

for(i in 1:length(x)){
	for (j in 1:length(y)){
		existed=TRUE
		k=1
		while(existed & k<=8){
			k=k+1
			anglei=sample(1:8,1)
			tox=i+changex[anglei]
			toy=j+changey[anglei]
			
			existed=any(fromto[,1]==tox & fromto[,2]==toy &
							fromto[,3]==i & fromto[,4]==j)
		}
		if(k>8){
			next()
		}else{
			fromto=rbind(fromto,c(i,j,tox,toy))
			angle=angles[anglei]
			xs=x[i]+cos(angle)*d
			ys=y[j]+sin(angle)*d
			samples=rbind(samples,cbind(xs,ys))
			
		}
		
	}
}

samples0=samples
samples[,1]=samples0[,2]
samples[,2]=samples0[,1]
grid0=grid
grid[,1]=grid0[,2]
grid[,2]=grid0[,1]
#最终的取样图保存在这个文件中
pdf("HSD soil sampling design.pdf",paper="a4",width=20,height=19)
plot(grid,pch=19,cex=0.7)
abline(h=x,lty=3)
abline(v=y,lty=3)
points(samples[seq(1,dim(samples)[1],3),],pch=19,col=3,cex=0.5)
points(samples[seq(2,dim(samples)[1],3),],pch=19,col=2,cex=0.5)
points(samples[seq(3,dim(samples)[1],3),],pch=19,col=4,cex=0.5)
dev.off()
grid=grid0
samples=samples0
#最终的取样量
dim(grid)[1]+dim(samples)[1]
